<template>
  <div class="newadd">
    <van-nav-bar
      title="新增地址"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />

    <main>
      <van-address-edit
        :area-list="areaList"
      
        show-set-default
        show-search-result
        :search-result="searchResult"
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="onSave"
        @delete="onDelete"
        @change-detail="onChangeDetail"
      />
    </main>
  </div>
</template>

<script>
import { Toast } from "vant";
import { areaList } from "@vant/area-data";
import { address_add,address_list} from "../../api/index2";

export default {
  data() {
    return {
      areaList,
      searchResult: [],
      lists:[]
    };
  },
  methods: {
    onClickLeft() {
      this.$router.back();
    },
    onSave(info) {
      console.log(info.areaCode)
      address_add({userid: localStorage.getItem("userid"),name:info.name,
      phone:info.tel,address:info.province+info.city+info.county+info.addressDetail
      ,areaCode:info.areaCode}).then((res) => {
        if(res.data.code == 200){
          // 获取所有的地址，再利用id去过滤出刚刚新增的那个对象，然后再往对应的对象里面新增一个属性areaCode 
          // 获取新的一共数组，再将其整个数据，传递到列表页，再到其列表页循环渲染出来，
          // 获取总共的地址列表 但是其中areaCode   
          address_list({userid:(localStorage.getItem("userid"))/1}).then((res)=>{
        if(res.data.code == 200){
            this.list = res.data.list
            console.log(this.list);
            
            this.list.forEach((item)=>{
                item.tel = item.phone;
                this.$set(this.list[this.list.length - 1],"areaCode",info.areaCode)
                console.log('this.list: ', this.list);
                this.list=this.lists;
            })
        }
    })
        // this.$router.push({path:"/MyAddress",query:{"areaCode":info.areaCode}})
        this.$router.go(-1);
        }
      });
    },
    onDelete() {
      Toast("delete");
    },
    onChangeDetail(val) {
      if (val) {
        this.searchResult = [
          {
            name: "黄龙万科中心",
            address: "杭州市西湖区",
          },
        ];
      } else {
        this.searchResult = [];
      }
    },
  },
};
</script>

<style lang="css" scoped>
.newadd {
  height: 100%;
}
</style>